package com.umeox.watch.moto.settings.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.umeox.watch.moto.settings.bean.SettingInfo;


public class SettingDaoImpl implements SettingDao {

    private static SettingDao sSettingDao;

    private Context mContext;

    private SettingSQLiteOpenHelper mSettingSQLiteOpenHelper;

    private SettingDaoImpl(Context context) {
        this.mContext = context;
        mSettingSQLiteOpenHelper = SettingSQLiteOpenHelper.getInstance(mContext);
    }

    public static SettingDao getInstance(Context context) {
        if (null == sSettingDao) {
            synchronized (SettingDaoImpl.class) {
                if (null == sSettingDao) {
                    sSettingDao = new SettingDaoImpl(context);
                }
            }
        }
        return sSettingDao;
    }

    @Override
    public synchronized long insert(SettingInfo info) {
        if (null == info) {
            throw new NullPointerException("info is not be null!");
        }
        SQLiteDatabase db = mSettingSQLiteOpenHelper.getWritableDatabase();
        db.execSQL("INSERT OR REPLACE into setting(_id, distanceUnit) values(?, ?)", new Object[]{info.getId(), info.getDistanceUnit()});
        return 0;
    }

    @Override
    public synchronized SettingInfo query() {
        final Cursor cursor = query(null, null, null, null);
        final SettingInfo info = new SettingInfo();
        if (cursor != null && cursor.moveToFirst()) {

            info.setId(cursor.getLong(cursor.getColumnIndex("_id")));
            info.setDistanceUnit(cursor.getInt(cursor.getColumnIndex(SettingDB.Column.DISTANCE_UNIT)));
            cursor.close();
            return info;
        }
        return info;
    }

    @Override
    public Cursor query(String[] columns, String selection, String[] selectionArgs, String orderBy) {
        SQLiteDatabase db = mSettingSQLiteOpenHelper.getReadableDatabase();
        final Cursor cursor = db.query(SettingDB.FACE_FEATURE, columns, selection, selectionArgs, null, null,
                orderBy);
        return cursor;
    }

    @Override
    public long insert(ContentValues values) {
        SQLiteDatabase db = mSettingSQLiteOpenHelper.getReadableDatabase();
        return db.replace(SettingDB.FACE_FEATURE, null, values);
    }


}
